package com.app.twth.ui.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.airsaid.pickerviewlibrary.OptionsPickerView;
import com.app.twth.R;
import com.app.twth.app.AppManager;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.databinding.ActivityLoginBinding;
import com.app.twth.slidingmenu.SlidingActivity;
import com.app.twth.statusbar.ScreenUtils;
import com.app.twth.statusbar.StatusBarUtil;
import com.app.twth.utils.CommonUtil;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.FastJsonUtil;
import com.app.twth.utils.PreferencesUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;


/**
 * ****************************************************************
 * 文件名称: LoginActivity
 * 文件描述:
 * 注意事项:
 * 版权声明:
 * ****************************************************************
 */
public class LoginActivity extends AppCompatActivity {
    protected Activity mContext;
    private ActivityLoginBinding binding;
    private LoginViewModel viewModel;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        ScreenUtils.setStatusBarTransparentAndWordsGray(getWindow());
        StatusBarUtil.setStatusBarLightMode(this, Color.WHITE);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        binding.setLifecycleOwner(this);
        setContentView(binding.getRoot());

        //事件监听
        initListener();
        //初始化数据
        initData();
        //页面事件监听的方法，一般用于ViewModel层转到View层的事件注册
        initViewObservable();

        AppManager.getInstance().finishOtherActivity(getClass());
    }

    private void initListener() {
        binding.etPwd.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                loginRequest();
                return true;
            }
            return false;
        });
        binding.btnLogin.setOnClickListener(v -> {
            loginRequest();
        });
    }

    private void initData() {
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(LoginViewModel.class);
        binding.setViewModel(viewModel);
    }

    private void initViewObservable() {
        viewModel.loginResultCode.observe(this, code -> {
            if (code.equals("200")) {
                Integer level = viewModel.loginResultData.getLevel();

                if (level == null) {
                    PreferencesUtil.putBoolean(mContext, Constant.isManager, false);
                } else {
                    if (level < 3) {
                        PreferencesUtil.putBoolean(mContext, Constant.isManager, true);
                    } else {
                        PreferencesUtil.putBoolean(mContext, Constant.isManager, false);
                    }
                }

                List<UserEntity.WarehouseListDTO> warehouseList = viewModel.loginResultData.getWarehouseList();
                if (warehouseList == null) {
                    CommonUtil.toast("该用户未配置仓库");
                    return;
                }
                PreferencesUtil.putString(this, Constant.userWarehouseList, FastJsonUtil.createJsonString(warehouseList));
                if (warehouseList.size() > 1) {//多个仓库
                    setPickerView();
                    return;
                }
                MyApplication.location = warehouseList.get(0).getId() + "";
                MyApplication.token = viewModel.loginResultData.getToken();
                Log.e("tag", "getToken:" + viewModel.loginResultData.getToken());
                PreferencesUtil.putString(mContext, Constant.USER_NAME, viewModel.userName.getValue());
                PreferencesUtil.putString(mContext, Constant.location, warehouseList.get(0).getId() + "");
                PreferencesUtil.putString(mContext, Constant.locationName, warehouseList.get(0).getCode() + "");
                PreferencesUtil.putString(mContext, Constant.token, viewModel.loginResultData.getToken());
                CrashReport.setUserId(viewModel.userName.getValue());  //该用户本次启动后的异常日志用户

                AppRouter.showFragmentActivity(mContext, SlidingActivity.class);
//                AppRouter.showFragmentActivity(mContext, MainActivity.class);
                finish();
            } else {
                if (!TextUtils.isEmpty(viewModel.loginResultMsg)) {
                    CommonUtil.toast(viewModel.loginResultMsg);
                }
                binding.btnLogin.setEnabled(true);
            }
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    private void showProgressDialog(String content) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setCancelable(true);
        }
        mProgressDialog.setMessage(content);
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        if (viewModel != null) {
            viewModel.dispose();
            viewModel = null;
        }
        super.onDestroy();
    }

    /**
     * 登录请求
     */
    private void loginRequest() {
        EditTextUtil.hideInput(this);
        boolean valid = true;
        if (TextUtils.isEmpty(viewModel.userName.getValue())) {
            valid = false;
            binding.llName.setError("Please enter a user name");
        } else {
            binding.llName.setErrorEnabled(false);
        }
        if (TextUtils.isEmpty(viewModel.password.getValue())) {
            valid = false;
            binding.llPwd.setError("Please enter a password");
        } else {
            binding.llPwd.setErrorEnabled(false);
        }
        if (valid) {
            binding.btnLogin.setEnabled(false);
            viewModel.login();
        }
    }

    private void setPickerView() {
        OptionsPickerView<UserEntity.WarehouseListDTO> mOptionsPickerView = new OptionsPickerView<>(mContext);
        // 设置数据
        mOptionsPickerView.setPicker(viewModel.loginResultData.getWarehouseList());
        mOptionsPickerView.setSelectOptions(-1);
        mOptionsPickerView.setCancelTextColor(R.color.color_666666);
        mOptionsPickerView.setSubmitText("Confirm");
        mOptionsPickerView.setCancelText("Cancel");
        // 设置点击外部是否消失
        mOptionsPickerView.setCancelable(false);
        mOptionsPickerView.setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int option1, int option2, int option3) {
                UserEntity.WarehouseListDTO userWarehouse = viewModel.loginResultData.getWarehouseList().get(option1);

                MyApplication.location = userWarehouse.getId() + "";
                MyApplication.token = viewModel.loginResultData.getToken();

                PreferencesUtil.putString(mContext, Constant.USER_NAME, viewModel.userName.getValue());
                PreferencesUtil.putString(mContext, Constant.location, userWarehouse.getId() + "");
                PreferencesUtil.putString(mContext, Constant.locationName, userWarehouse.getCode() + "");
                PreferencesUtil.putString(mContext, Constant.token, viewModel.loginResultData.getToken());

                mOptionsPickerView.dismiss();
                startActivity(new Intent(mContext, SlidingActivity.class));
//                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        });
        mOptionsPickerView.show();
    }
}
